package cn.ac.iie.di.ban.ycl.cleaner.sender;

import cn.ac.iie.di.ban.ycl.cleaner.CleanerMain;
import cn.ac.iie.di.ban.ycl.cleaner.common.Constants;
import cn.ac.iie.di.ban.ycl.cleaner.common.RedisUtil;
import java.util.Map;
import org.apache.commons.configuration2.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author zmc <zhangmingcheng@iie.ac.cn>
 * @date 2016-11-8 11:14:11
 * @version V1.0
 * @desc
 */
public class CtReceiveCountSenderThread implements Runnable {

    private static final Logger LOG = LoggerFactory.getLogger(CtReceiveCountSenderThread.class);
    RedisUtil redisUtil;
    static final String TWX_IVR_CT_RECEIVE_TIME_PREFIX = "twx_ivr_ct_receive_time_";
    static final String TWX_G_CT_RECEIVE_TIME_PREFIX = "twx_g_ct_receive_time_";

    public CtReceiveCountSenderThread(Configuration conf) {
        String redisHost = conf.getString(Constants.REDIS_HOSTS);
        String redisMasterName = conf.getString(Constants.REDIS_MASTER_NAME);
        int dbName = conf.getInt(Constants.REDIS_DB_NAME);
        redisUtil = new RedisUtil(redisHost, redisMasterName, dbName);
    }

    @Override
    public void run() {
        LOG.info("ct receive count send thread start!");
        while (true) {
            try {
                Map<String, Integer> message = (Map<String, Integer>) CleanerMain.cTReceiveCountQueue.take();
                if (message == null) {
                    continue;
                }
                for (Map.Entry<String, Integer> entrySet : message.entrySet()) {
                    String key = entrySet.getKey();
                    Integer value = entrySet.getValue();
                    if (CleanerMain.isIvrMsg) {
                        redisUtil.incrBy(TWX_IVR_CT_RECEIVE_TIME_PREFIX + key, Long.valueOf(value.toString()));
                    } else {
                        redisUtil.incrBy(TWX_G_CT_RECEIVE_TIME_PREFIX + key, Long.valueOf(value.toString()));
                    }
                }
            } catch (InterruptedException | NumberFormatException ex) {
                LOG.error("ct receive count messages error!", ex);
            }
        }
    }

}
